package com.mifengs.mall.ui.login;

import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mifengs.commonbase.util.StatusBarCompat;
import com.mifengs.commonbase.util.StatusBarUtils;
import com.mifengs.mall.Constant;
import com.mifengs.mall.R;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.mall.di.component.DaggerLoginComponent;
import com.mifengs.mall.di.module.LoginModule;
import com.mifengs.mall.event.LoginEvent;
import com.mifengs.mall.event.MainEvent;
import com.mifengs.mall.util.UIUtil;
import com.mifengs.mall.widget.VerifyCodeView;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Map;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Route(path = "/mifengapp/login")
public class LoginActivity extends BaseActivity<LoginPresent> implements LoginContract.View {

    @BindView(R.id.v_status)
    View vStatus;
    @BindView(R.id.et_iphone)
    EditText mEtIphone;
    @BindView(R.id.et_password)
    EditText mEtPassword;
    @BindView(R.id.iv_eye)
    ImageView mIvEye;
    @BindView(R.id.ll_weixin)
    LinearLayout ll_wx_login;
    @BindView(R.id.ll_code)
    LinearLayout mLlCode;
    @BindView(R.id.et_verity_code)
    EditText mEtVerityCode;
    @BindView(R.id.btn_photo_code)
    VerifyCodeView mPhotoCodeWebView;
    @BindView(R.id.iv_delete)
    ImageView mIvDelete;
    @BindView(R.id.login)
    TextView mBtLogin;
    private boolean mDisplayFlg = false;
    private boolean isHasPhone = false;
    private boolean isHasPwd = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_login);
        ButterKnife.bind(this);
        StatusBarCompat.setStartBarTranslucent(this);
        StatusBarUtils.StatusBarLightMode(this);
        EventBus.getDefault().register(this);
        setStatusBarHeight();
        init();
    }

    private void init() {
        mPhotoCodeWebView.loadUrl(Constant.PHONE_CODE);
        mPhotoCodeWebView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mPhotoCodeWebView.reload();
                return false;
            }
        });
        mEtIphone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    mIvDelete.setVisibility(View.INVISIBLE);
                    isHasPhone = false;
                    mBtLogin.setBackgroundResource(R.drawable.btn_not_select);
                } else {
                    mIvDelete.setVisibility(View.VISIBLE);
                    isHasPhone = true;
                    if (isHasPwd) {
                        mBtLogin.setBackgroundResource(R.drawable.btn_select);
                    }else{
                        mBtLogin.setBackgroundResource(R.drawable.btn_not_select);
                    }
                }
                mLlCode.setVisibility(View.GONE);
                mEtVerityCode.setText("");
            }
        });
        mEtPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (TextUtils.isEmpty(s.toString())) {
                    isHasPwd = false;
                    mBtLogin.setBackgroundResource(R.drawable.btn_not_select);
                } else {
                    isHasPwd = true;
                    if (isHasPhone) {
                        mBtLogin.setBackgroundResource(R.drawable.btn_select);
                    }else{
                        mBtLogin.setBackgroundResource(R.drawable.btn_not_select);
                    }
                }
            }
        });
    }


    @Override
    public void initInjector() {
        DaggerLoginComponent.builder()
                .loginModule(new LoginModule(this))
                .build()
                .inject(this);
    }


    private void setStatusBarHeight() {
        int statusHeight = UIUtil.getStatusHight();
        ConstraintLayout.LayoutParams layoutParams = (ConstraintLayout.LayoutParams) vStatus.getLayoutParams();
        layoutParams.setMargins(0, statusHeight, 0, 0);
    }

    @OnClick({R.id.fl_delete, R.id.tv_forget, R.id.iv_eye, R.id.ll_weixin, R.id.ll_register, R.id.login, R.id.iv_delete})
    public void onViewClicked(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.fl_delete:
                finish();
                break;
            case R.id.tv_forget:
                intent = new Intent(this, RetrievePasswordActivity.class);
                startActivity(intent);
                break;
            case R.id.iv_eye:
                passwordTransformation();
                break;
            case R.id.ll_weixin:
                UMShareAPI.get(this).getPlatformInfo(LoginActivity.this, SHARE_MEDIA.WEIXIN, umAuthListener);
//                intent = new Intent(this, CompletePasswordActivity.class);
//                startActivity(intent);
                break;
            case R.id.ll_register:
                intent = new Intent(this, NewRegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.login:
                login();
                break;
            case R.id.iv_delete:
                mEtIphone.setText("");
                mIvDelete.setVisibility(View.GONE);
                break;
        }
    }

    private void login() {
        if(!isHasPhone){
            showLongToast("请填写手机号");
            return;
        }
        if(!isHasPwd){
            showLongToast("请填写密码");
            return;
        }

        mPresenter.login();
    }


    private void passwordTransformation() {

        if (!mDisplayFlg) {
            // display password text, for example "123456"
            mEtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            // hide password, display "."
            mEtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

        mDisplayFlg = !mDisplayFlg;

        mEtPassword.postInvalidate();

        if (mDisplayFlg) {
            mIvEye.setImageResource(R.drawable.ic_input_xianshi);
        } else {
            mIvEye.setImageResource(R.drawable.ic_input_noxianshi);
        }

    }


    @Override
    public String getPwd() {
        return mEtPassword.getText().toString();
    }

    @Override
    public String getAccount() {
        return mEtIphone.getText().toString();
    }

    @Override
    public void hideOrShowCodeView(boolean isShow) {
        if (isShow) {
            mLlCode.setVisibility(View.VISIBLE);
        } else {
            mLlCode.setVisibility(View.GONE);
        }
    }

    @Override
    public String getVerifyCode() {
        return mEtVerityCode.getText().toString();
    }

    @Override
    public void toVerifyPhone(String weixinJson) {
        Intent intent = new Intent(this,VerifyPhoneActivity.class);
        intent.putExtra("weixinJson",weixinJson);
        startActivity(intent);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }


    private UMAuthListener umAuthListener = new UMAuthListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            //授权开始的回调
        }

        @Override
        public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
            //Toast.makeText(getApplicationContext(), "Authorize succeed", Toast.LENGTH_SHORT).show();
            Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
            String weixinJson = gson.toJson(data);
            if(!TextUtils.isEmpty(weixinJson)){
                mPresenter.weixinLogin(weixinJson);
            }else{
                showLongToast("授权失败");
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, int action, Throwable t) {
//            Toast.makeText(getApplicationContext(), "Authorize fail", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform, int action) {
//            Toast.makeText(getApplicationContext(), "Authorize cancel", Toast.LENGTH_SHORT).show();
        }
    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLoginEvent(LoginEvent event) {
        switch (event.action) {
            case LoginEvent.LOGIN_SUCCESS:
                EventBus.getDefault().post(new MainEvent(MainEvent.LOGINTRELOAD));
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
